// miniprogram/pages/create/create.js
import {
  queryAllActivity
} from "./../../api/activity.js"
import {
  create
} from "../../api/solitaire.js"
import {
  isEmpty
} from './../../utils/utils.js'
import {
  addUser
} from './../../api/users.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activitys: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      canIUseGetUserProfile: app.globalData.canIUseGetUserProfile
    })
    queryAllActivity().then(res => {
      console.log("queryAllActivity", res)
      this.data.activitys = res.result.data
    })
  },

  //选择活动
  onChooseActivitys() {
    if (this.data.activitys.length > 0) {
      const that = this
      wx.showActionSheet({
        itemList: this.data.activitys.map(item => item.name),
        success(res) {
          const item = that.data.activitys[res.tapIndex]
          that.setData({
            currentActivity: item
          })
        }
      })
    }
  },
  onTitleInput(e) {
    this.data.title = e.detail.value
  },
  onRemarksInput(e) {
    this.data.remarks = e.detail.value
  },
  onBtnCancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  getUserInfo(e) {
    console.log("getUserInfo", e.detail.userInfo)
    const userInfo = e.detail.userInfo
    if (isEmpty(userInfo)) {
      wx.showToast({
        title: '授权失败',
        icon: 'error'
      })
      return
    }
    if (isEmpty(app.globalData.userInfo)) {
      addUser(userInfo).then(res => {
        //用户信息保存到缓存，下次不用授权了
        app.globalData.userInfo = userInfo
        this.create()
      })
    } else {
      this.create()
    }
  },
  onBtnSumbit() {
    //当前没有用户信息，授权获取用户信息
    if (isEmpty(app.globalData.userInfo)) {
      wx.getUserProfile({
        desc: '获取头像和昵称'
      }).then(res => {
        this.getUserInfo({
          detail: {
            userInfo: res.userInfo
          }
        })

      }).catch(res => {
        //拒绝授权
        this.getUserInfo({
          detail: {
            userInfo: undefined
          }
        })
      })
    } else {
      this.create()
    }
  },
  create() {
    if (isEmpty(this.data.currentActivity)) {
      wx.showToast({
        title: '请选择活动',
        icon: "error"
      })
      return
    }
    if (isEmpty(this.data.title)) {
      wx.showToast({
        title: '请填写主题',
        icon: "error"
      })
      return
    }
    if (isEmpty(this.data.remarks)) {
      wx.showToast({
        title: '请填写备注',
        icon: "error"
      })
      return
    }
    wx.showLoading({
      title: '请稍等...',
    })
    create({
      activity: this.data.currentActivity.type,
      title: this.data.title,
      remarks: this.data.remarks
    }).then(res => {
      wx.hideLoading()
      wx.navigateBack({
        delta: 1,
      })
    })
  }
})